package org.example.userservice.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.userservice.service.UserService;
import org.example.userservice.VO.UserVO;
import org.example.userservice.entity.User;
import org.example.userservice.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     * POST /user/register
     */
    @PostMapping("/register")
    public String register(@RequestBody User user,HttpServletRequest request) {
        userService.register(user,request);
        return "注册成功！";
    }

    /**
     * 用户登录
     * POST /user/login
     */
    @PostMapping("/login")
    public String login(@RequestBody User user,HttpServletRequest request) {
        return userService.login(user,request);
    }

    /**
     * 查询所有用户
     * GET /user/users
     */
    @GetMapping("/users")
    public List<UserVO> listUsers(HttpServletRequest request) {
        return userService.listUsers(request);
    }

    /**
     * 查询单个用户
     * GET /user/{userId}
     */
    @GetMapping("/{userId}")
    public UserVO getUser(@PathVariable Long userId,HttpServletRequest request) {
        return userService.selectUserById(userId,request);
    }

    /**
     * 更新用户信息
     * PUT /user/{userId}
     */
    @PutMapping("/{userId}")
    public String updateUser(@PathVariable Long userId,@RequestBody User user,HttpServletRequest request) {
        User check = userMapper.findById(userId);
        if (check == null) {
            return "此ID不存在！";
        }
        // 设置要更新的用户ID
        user.setUserId(userId);
        // 调用服务层执行更新
        return userService.update(user,request);
    }

    /**
     * 修改密码
     * POST /user/reset-password
     */
    @PostMapping("/reset-password")
    public String resetpassword(@RequestBody User user,HttpServletRequest request) {
        User check = userMapper.findById(user.getUserId());
        if (check == null) {
            return "此用户不存在！";
        }
        // 调用服务层执行更新
        return userService.resetPassword(user,request);
    }

}